<template>
	<view class="">
		<loading ref="loading"></loading>
		<view class="" v-if="loadFlag">
			<u-navbar :is-back="false" :title="vk.getVuex('$setting.base.search')?vk.getVuex('$setting.base.name'):' '" :background="{backgroundColor: vk.getVuex('$app.config.bg.navbar')}" :title-color="vk.getVuex('$app.config.color.main')" :border-bottom="false">
				<view class="slot-wrap">
					<view class="u-flex u-row-between" style="width: 100%;" v-if="!vk.getVuex('$setting.base.search')">
						<view class="" style="width: 52rpx;height: 52rpx;position: relative;">
							<u-icon name="/static/icon/shares.png" size="52"></u-icon>
							<button open-type="share" style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;opacity: 0;"></button>
						</view>
						<view class="search u-flex u-row-left" @click="search" style="z-index: 1000;" :style="{color: vk.getVuex('$app.config.color.light'),background: vk.getVuex('$app.config.bg.search')}">
							<u-icon name="/static/search.png" size="28"></u-icon>
							<text class="u-p-l-15">请输入关键字搜索</text>
						</view>
					</view>
				</view>
			</u-navbar>
			<!-- #ifdef MP -->
			<add-tips v-if="!vk.getVuex('$setting.base.search')" tip="点击「添加小程序」更新早知道" :top="navHeight - 10" :duration="3" />
			<!-- #endif -->
			<view class="" v-if="vk.getVuex('$setting.base.search')">
				<view class="u-flex-col u-row-right u-col-center" style="height: 46vh;">
					<view class="">
						<image class="logo" :src="vk.getVuex('$setting.base.logo')" :background="{borderColor: vk.getVuex('$app.config.bg.navbar')}"></image>
					</view>
					<view class="u-flex u-row-center u-p-t-80">
						<view class="input">
							<input v-model="searchText"
							placeholder-style="color:#a6a7a8;font-size:14px;" 
							placeholder="请输入关键字搜索" />
						</view>
						<view class="btn" @click="getSearchText">搜索</view>
					</view>
				</view>
			</view>
			<view class="" v-else>
				<view class="u-p-t-15 u-p-l-20 u-p-r-20">
					<u-swiper
						height="300"
						bg-color="rgba(0,0,0,0)"
						name="image"
						:interval="4000"
						border-radius="16"
						:list="bannerList"
						@click="bannerClick"
					></u-swiper>
				</view>
				<view class="u-p-b-10 u-m-t-20" v-if="specialList.length > 0">
					<view class="u-p-l-20 u-p-r-20">
						<u-section
							title="专题推荐"
							:color="vk.getVuex('$app.config.color.main')"
							:sub-color="vk.getVuex('$app.config.color.sec')"
							:line-color="vk.getVuex('$app.config.color.sec')"
							:bold="false"
							font-size="32"
							sub-title="查看更多"
							@click="specialClick"
						></u-section>
					</view>
					<view class="u-flex u-row-left u-flex-wrap u-p-l-20 u-m-t-20">
						<view class="bg-white u-m-r-15 xilie" v-for="(item, index) in specialList" :key="index" @click="seriesDetail(item._id)">
							<image lazy-load :src="item.image + (vk.getVuex('$setting.thumb.special_flag') === 1 ? vk.getVuex('$setting.thumb.special_style') : '')" mode="aspectFill"></image>
							<view class="u-line-1" style="position: absolute;bottom: 15rpx;left: 15rpx;width: 250rpx;color: #FFFFFF;">{{item.title}}</view>
						</view>
					</view>
				</view>
				<view class="u-p-t-10" v-if="avatarList.length > 0">
					<view class="u-p-l-20 u-p-r-20">
						<u-section
							title="头像推荐"
							:color="vk.getVuex('$app.config.color.main')"
							:sub-color="vk.getVuex('$app.config.color.sec')"
							:line-color="vk.getVuex('$app.config.color.sec')"
							:bold="false"
							font-size="32"
							sub-title="查看更多"
							@click="avatarClick"
						></u-section>
					</view>
					<scroll-view scroll-x class="u-p-t-20 u-p-l-20 u-p-r-20" style="height: 180rpx;width: calc(100% - 40rpx);">
						<view class="u-flex u-row-left ">
							<block v-for="(item, index) in avatarList" :key="index">
								<block v-for="(item_, index_) in item.images" :key="index_" v-if="index_ < 2">
									<view class="tab" @click="avatarDetail(item._id, index_)">
										<image lazy-load
											:src="item_ + (vk.getVuex('$setting.thumb.avatar_flag') === 1 ? vk.getVuex('$setting.thumb.avatar_style') : '')"
											style="width: 180rpx;height: 180rpx;"
											mode="aspectFill"
										></image>
										<!-- <view class="array">{{item.images.length}}</view> -->
										<!-- <images lazy-load :width="180" :height="180" :radius="12" :src="item_+(vk.getVuex('$setting.thumb.avatar_flag')===1?vk.getVuex('$setting.thumb.avatar_style'):'')" mode="aspectFill"></images> -->
									</view>
								</block>
							</block>
						</view>
					</scroll-view>
				</view>
				<view class="u-m-t-10" style="position: sticky;z-index: 9;width: 100%;" :style="{top: navHeight+'rpx'}">
					<u-tabs
						:duration="0"
						:list="cateList"
						height="60"
						:is-scroll="true"
						gutter="18"
						name="hname"
						:active-color="vk.getVuex('$app.config.color.sec')"
						:inactive-color="vk.getVuex('$app.config.color.main')"
						:bg-color="vk.getVuex('$app.config.bg.navbar')"
						bar-height="6"
						bar-width="40"
						:current="cateStatic"
						@change="cateClick"
					></u-tabs>
				</view>
				<view class="u-flex u-row-left u-flex-wrap u-p-l-20 u-p-t-10">
					<block v-for="(item, index) in coverList" :key="index">
						<block v-for="(item_, index_) in item.images_" :key="index_">
							<view class="tab" v-if="item_.ind != 0 && item_.ind % 18 === 0">
								<view class="" style="width: 710rpx;">
									<ad v-if="vk.getVuex('$setting.client.banner_id')" :unit-id="vk.getVuex('$setting.client.banner_id')" type="banner" ad-theme="black"></ad>
								</view>
							</view>
							<view class="tab" @click="detail(item._id, index_)">
								<!-- <image
									lazy-load
									:src="item_.img + (vk.getVuex('$setting.thumb.cover_flag') === 1 ? vk.getVuex('$setting.thumb.cover_style') : '')"
									mode="aspectFill"
								></image> -->
								<muqian-lazyLoad width="226rpx" height="360rpx" :src="item_.img + (vk.getVuex('$setting.thumb.cover_flag') === 1 ? vk.getVuex('$setting.thumb.cover_style') : '')"></muqian-lazyLoad>
							</view>
						</block>
					</block>
				</view>
				
				<view class="" v-if="!noData"><u-loadmore :status="loadStatus" font-size="24" :margin-top="30" :margin-bottom="30" color="#B8B8B8" /></view>
				<nodata v-else></nodata>
				
				<view class="safe-area-inset-bottom"><view class="" style="height: 1rpx;"></view></view>
				
				<view @click="backTop" class="back backTop u-flex u-flex-col u-row-center u-col-center" :class="backShow ? 'backTop_show' : 'backTop_hide'">
					<image src="/static/backtop.png" style="width: 36rpx;height: 36rpx;"></image>
					<view class="text">顶部</view>
				</view>
				<view @click="search" class="back backSearch u-flex u-flex-col u-row-center u-col-center" :class="backShow ? 'backTop_show' : 'backTop_hide'">
					<image src="/static/search_t.png" style="width: 30rpx;height: 30rpx;"></image>
					<view class="text">搜索</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	let systemInfo = uni.getSystemInfoSync();
	// px转换到rpx的比例
	let pxToRpxScale = 750 / systemInfo.windowWidth;
	// 状态栏的高度
	let ktxStatusHeight = systemInfo.statusBarHeight * pxToRpxScale;
	// 导航栏的高度
	let navigationHeight = 44 * pxToRpxScale;
	// 总高度
	let navHeight = ktxStatusHeight + navigationHeight;
	// #ifdef MP
	import addTips from '@/components/add-tips/add-tips.vue';
	// #endif
	export default {
		components: {
			// #ifdef MP
			addTips
			// #endif
		},
		data() {
			return {
				loadFlag: false,
				navHeight: navHeight,
				// 加载
				scrollTop: 0,
				// 首页数据
				bannerList: [],
				avatarList: [],
				specialList: [],
				coverList: [],
				cateStatic: 0,
				cateList: [{ name: '最新' }, { name: '热门' }],
				// 下拉
				pageIndex: 0,
				loadStatus: 'loading',
				// 滚动的位置
				backShow: false,
				noData: false,
				imageIndex: 0,
				searchText: ''
			};
		},
		async onLoad(options) {
			let that = this;
			if (options.inviteId) uni.setStorageSync('inviteId', options.inviteId);
			await that.getHome();
			that.loadFlag = true
			that.$nextTick(() => {
				that.$refs.loading.closeLoading()
			})
			await that.getList();
			const updateManager = uni.getUpdateManager();
		
			updateManager.onCheckForUpdate(function(res) {
				// 请求完新版本信息的回调
				if (!res.hasUpdate && options.detailId) {
					uni.showLoading({
						mask: true,
						title: '正在跳转...'
					});
					setTimeout(function() {
						uni.hideLoading();
						if (options.type === 'detail') uni.navigateTo({ url: '/pages/detail/detail?id=' + options.detailId + '&index=' + options.index });
						if (options.type === 'avatar') uni.navigateTo({ url: '/pages/detail/avatar?id=' + options.detailId + '&index=' + options.index });
						if (options.type === 'look') uni.navigateTo({ url: '/pages/detail/look?id=' + options.detailId + '&index=' + options.index });
						if (options.type === 'special') uni.navigateTo({ url: '/pages/detail/special?id=' + options.detailId });
						if (options.type === 'trends') uni.navigateTo({ url: '/pages/trends/detail?id=' + options.detailId });
						if (options.type === 'home') uni.navigateTo({ url: '/pages/write/home?id=' + options.detailId });
					}, 1800);
				}
			});
		
			updateManager.onUpdateReady(function(res) {
				uni.showModal({
					title: '更新提示',
					content: '新版本已经准备好，是否重启应用？',
					success(res) {
						if (res.confirm) {
							// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
							updateManager.applyUpdate();
						}
					}
				});
			});
		},
		onShow() {
			let that = this;
			that.getSetting();
		},
		methods: {
			// 首页
			async getHome() {
				let that = this;
				let data = await that.vk.callFunction({
					url: 'client/wechat/list/pub/getHome',
				});
				that.vk.setVuex('$setting.thumb', data.thumb);
				that.bannerList = data.advert.rows;
				that.specialList = data.special.rows;
				that.avatarList = data.avatar.rows;
				that.cateList = that.cateList.concat(data.category.rows);
			},
			async getSetting() {
				let that = this;
				let data = await that.vk.callFunction({
					url: 'client/wechat/list/pub/getSetting'
				});
				that.vk.setVuex('$setting.base', data.base_config);
				that.vk.setVuex('$setting.client', data.client_config);
				that.vk.setVuex('$setting.score', data.score_config);
			},
			cateClick(e, t) {
				var that = this;
				that.noData = false;
				that.cateStatic = e;
				that.imageIndex = 0;
				that.getList(1);
			},
			async getList(on) {
				let that = this;

				var newList = that.coverList;
				// 点击切换菜单 回复初始状态
				if (on == 1) {
					uni.showLoading({
						mask: true,
						title: '加载中...'
					});
					newList = [];
					that.pageIndex = 0;
				}
				that.pageIndex = that.pageIndex + 1;
				that.loadStatus = 'loading';

				let sortArr = [{ name: '_add_time', type: 'desc' }];
				var whereJson = { category_id: that.cateList[that.cateStatic]._id, mode: 0, status: 1 };
				if (that.cateStatic === 0) {
					whereJson = { mode: 0, status: 1 };
				} else if (that.cateStatic === 1) {
					whereJson = { mode: 0, status: 1 };
					sortArr = [{ name: 'view', type: 'desc' }];
				}
				let data = await that.vk.callFunction({
					url: 'client/wechat/list/pub/getList',
					data: {
						dbName: 'bus-wx-cover',
						pageIndex: that.pageIndex,
						pageSize: 30,
						whereJson: whereJson,
						sortArr: sortArr
					}
				});
				for (var i = 0; i < data.rows.length; i++) {
					var images_ = [];
					for (var j = 0; j < data.rows[i].images.length; j++) {
						images_.push({
							ind: that.imageIndex,
							img: data.rows[i].images[j]
						});
						that.imageIndex++;
					}
					data.rows[i].images_ = images_;
				}
				that.coverList = newList.concat(data.rows);
				if (data.hasMore) that.loadStatus = 'loadmore';
				else that.loadStatus = 'nomore';
				if (data.total == 0) that.noData = true;
				else that.noData = false;
				uni.hideLoading()
			},
			search() {
				uni.navigateTo({
					url: '/pages/about/search'
				});
			},
			backTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
			},
			word(){
				uni.navigateTo({
					url: '/pages/about/word'
				});
			},
			bannerClick(index) {
				let that = this
				var advert = this.bannerList[index];
				if (advert.plan === 0) {
					uni.navigateTo({
						url: '/pages/detail/detail?id=' + advert.detail_id + '&index=0'
					});
				} else if (advert.plan === 1) {
					uni.navigateTo({
						url: '/pages/detail/avatar?id=' + advert.detail_id + '&index=0'
					});
				} else if (advert.plan === 2) {
					uni.navigateTo({
						url: '/pages/trends/detail?id=' + advert.detail_id
					});
				} else if (advert.plan === 3) {
					uni.navigateTo({
						url: '/pages/detail/special?id=' + advert.special_id
					});
				} else if (advert.plan === 4) {
					uni.navigateToMiniProgram({
						appId: advert.appid,
						path: advert.pages,
						success(res) {}
					});
				} else if (advert.plan === 5) {
					uni.navigateTo({
						url: '/pages/about/link?url=' + encodeURIComponent(advert.url) + '&name=' + advert.name
					});
				} else if (advert.plan === 6) {
					if(advert.pages === '/pages/write/auth'){
						if(that.vk.getVuex('$setting.client.verify')){
							uni.navigateTo({
								url: '/pages/write/stats'
							})
							return
						}
						if(that.vk.getVuex('$user.userInfo.auth.status') === 1){
							uni.navigateTo({
								url: '/pages/write/stats'
							})
						}else{
							uni.navigateTo({
								url: '/pages/write/auth'
							})
						}
					}else{
						uni.navigateTo({
							url: advert.pages
						});
					}
				}
			},
			detail(id, index) {
				uni.navigateTo({
					url: '/pages/detail/detail?id=' + id + '&index=' + index
				});
			},
			avatarDetail(id, index) {
				uni.navigateTo({
					url: '/pages/detail/avatar?id=' + id + '&index=' + index
				});
			},
			listClick(type, pid, id) {
				uni.navigateTo({
					url: '/pages/list/list?type=' + type + '&pid=' + pid + '&id=' + id
				});
			},
			avatarClick() {
				uni.navigateTo({
					url: '/pages/list/avatar'
				});
			},
			seriesDetail(id) {
				uni.navigateTo({
					url: '/pages/detail/special?id=' + id
				});
			},
			specialClick() {
				uni.navigateTo({
					url: '/pages/list/special'
				});
			},
			specialDetail(id) {
				uni.navigateTo({
					url: '/pages/detail/special'
				});
			},
			async getSearchText() {
				if(this.isSearch){
					uni.showToast({
						icon: 'none',
						title: '太快啦，歇一会再试试',
						mask: true,
						duration: 1000
					})
					return
				}
				this.isSearch = true
				let e = this.searchText
				
				let data = {}
				uni.showLoading({
					mask: true,
					title: '搜索中...'
				})
				data = await this.vk.callFunction({
					url: 'client/wechat/list/pub/findWhere',
					data:{
						dbName: 'bus-wx-auth',
						whereJson: {
							code: e
						}
					}
				})
				if(data.info){
					uni.navigateTo({
						url: '/pages/write/home?id='+data.info.user_id
					})
					this.isSearch = false
					uni.hideLoading()
					return
				}
				data = await this.vk.callFunction({
					url: 'client/wechat/list/pub/findWhere',
					data:{
						dbName: 'bus-wx-cover',
						whereJson: {
							code: parseInt(e)
						}
					}
				});
				if(data.info && data.info.mode===0){
					uni.navigateTo({
						url: '/pages/detail/detail?index=0&id='+data.info._id
					})
				}else if(data.info && data.info.mode===1){
					uni.navigateTo({
						url: '/pages/detail/avatar?index=0&id='+data.info._id
					})
				}else if(data.info && data.info.mode===2){
					uni.navigateTo({
						url: '/pages/trends/detail?index=0&id='+data.info._id
					})
				}else{
					uni.navigateTo({
						url: '/pages/list/list?type=search&value='+e
					})
				}
				this.isSearch = false
				uni.hideLoading()
				return
			}
		},
		async onReachBottom() {
			let that = this;
			if (that.loadStatus == 'nomore') return;
			await that.getList();
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
			if (e.scrollTop > 1000) {
				this.backShow = true;
			} else {
				this.backShow = false;
			}
		},
		onShareAppMessage(res) {
			return {
				title: '这里有超多好看的壁纸免费下载~',
				imageUrl: this.vk.getVuex('$setting.base.image'),
				path: 'pages/index/index?inviteId=' + (this.vk.getVuex('$user.userInfo._id') ? this.vk.getVuex('$user.userInfo._id') : '')
			};
		}
	};
</script>
<style lang="scss" scoped>
	.slot-wrap {
		display: flex;
		align-items: center;
		flex: 1;
		padding: 0 30rpx;
	}
	.search {
		height: 58rpx;
		margin-left: 25rpx;
		padding-left: 30rpx;
		border-radius: 50px;
		width: 100%;
		text {
			color: #808080;
			font-size: 13px;
		}
	}
	.tab {
		position: relative;
		border-radius: 12rpx;
		margin-right: 16rpx;
		margin-bottom: 16rpx;
		image {
			border-radius: 12rpx;
			width: 226rpx;
			height: 360rpx;
		}
		.array {
			position: absolute;
			top: 18rpx;
			right: 0rpx;
			color: #f8de52;
			background-color: rgba(0, 0, 0, 0.4);
			padding: 0rpx 12rpx 0 16rpx;
			border-radius: 20rpx 0 0 20rpx;
			font-size: 12px;
		}
	}

	.xilie {
		width: calc(50% - 17.5rpx);
		position: relative;
		image {
			width: 100%;
			height: 200rpx;
			border-radius: 12rpx;
		}
		.bill {
			width: 100%;
			position: absolute;
			bottom: 0;
			left: 0;
			background-color: rgba(0, 0, 0, 0.2);
			color: #ffffff;
			font-size: 13px;
			text-align: center;
		}
	}

	.back {
		z-index: 999;
		position: fixed;
		right: -80rpx;
		width: 80rpx;
		height: 80rpx;
		border-radius: 80rpx;
		padding: 8rpx;
		box-shadow: 0 0px 16px rgba(0, 0, 0, 0.2);
		transition-property: right;
		transition-duration: 0.6s;
		.text {
			font-size: 12px;
		}
	}
	.backSearch {
		bottom: 150rpx;
		background-color: #efb336;
		.text {
			color: #ffffff;
		}
	}
	.backTop {
		bottom: 50rpx;
		background-color: #ffffff;
		.text {
			color: #efb336;
		}
	}
	.backTop_show {
		right: 20rpx !important;
	}
	.backTop_hide {
		right: -80rpx !important;
	}
	.hover-class{
		transform:scale(0.95);
		transition: all 0.2s;
	}

	// 搜索框
	.input {
		border-radius: 12rpx 0 0 12rpx;
		width: calc(100vw - 240rpx);
		input{
			line-height: 100rpx;
			height: 100rpx;
			padding-left: 30rpx;
			padding-right: 30rpx;
		}
	}
	.btn{
		width: 160rpx;
		text-align: center;
		background-image: linear-gradient(to right, #65A0EE , #836AF0);
		border-radius: 0 12rpx 12rpx 0;
		line-height: 99rpx;
		height: 99rpx;
	}
	.logo{
		border: 4px solid;
		width: 180rpx;
		height: 180rpx;
		border-radius: 180rpx;
	}
</style>
